<template>
  <div class="box">
    <el-card class="card">
      <el-form label-width="200px">
        <el-form-item label="商品名称">
          <el-input v-model="title" style="width: calc(100% - 300px)" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="二级标题">
          <el-input v-model="secondtitle" style="width: calc(100% - 300px)" placeholder="请输入二级标题"/>
        </el-form-item>
        <el-form-item label="商品详情">
          <el-input
            v-model="details"
            type="textarea"
            :rows="4"
            style="width: calc(100% - 300px)"
            placeholder="请输入商品详情"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            :headers="img_token"
            class="avatar-uploader"
            :action="img_up+ '/p/goods/pcInsert'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否开售">
          <el-radio-group v-model="radio">
            <el-radio :label="1">开</el-radio>
            <el-radio :label="2">关</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="presentprice" style="width: calc(100% - 300px)" placeholder="请输入原价">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="现价">
          <el-input v-model="originalprice" style="width: calc(100% - 300px)" placeholder="请输入现价">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="stock" style="width: calc(100% - 300px)" placeholder="请输入现价">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="轮播图">
          <el-upload
            class="upload-demo"
            drag
            :headers="img_token"
            :on-success="handleAvatarSuccess2"
            :on-remove="handleRemove"
            :action="img_up+ '/p/goods/pcInsert'"
            :file-list="imgList"
            list-type="picture"
          >
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="remarks"
            type="textarea"
            :rows="8"
            style="width: calc(100% - 300px)"
            placeholder="请输入备注"
          />
        </el-form-item>

      </el-form>
      <div class="button">
        <el-button>重置</el-button>
        <el-button type="primary" @click="ischange()">提交</el-button>
        <el-button type="primary" v-if="back" @click="goBack()">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
  import { getToken } from '../../utils/auth'
  import { http_URL, IMG_URL } from '../../utils/global'
  import { goodsCategoryList } from '../../api/cate'
  import { addGoods, goodsDetail, goodsUpdate } from '../../api/goods'

  export default {
    name: 'GoodsAdd',
    data() {
      return {
        img_token: {
          token: getToken()
        },
        img_up: http_URL,
        img_url: IMG_URL,
        imageUrl: '', // 本地图片地址

        value: '',
        options: [], // 分类商品数组
        radio: 1,
        imgList: [], // 数组

        title: '', // 商品标题
        details: '', // 商品详情
        remarks: '', // 备注
        secondtitle: '', // 二级标题
        stock: '', // 库存
        presentprice: '', // 现价
        originalprice: '', // 原价
        isopen: '', // 是否开启 1是 2否
        imgurl: '', // 后台商品图片
        imglist: '', // 商品轮播图(json字符串)
        categoryid: '', // 分类id

        isEditOrDetailId: '',  //详情或编辑id
        back: '' // 按钮显现

      }
    },
    created() {
      this.goodsCategoryList()
      if (this.$route.query.idEdit) {
        this.isEditOrDetailId = this.$route.query.idEdit
        this.back = this.$route.query.back
        this.goodsDetail() // 获取详情
      }
    },
    methods: {
      //修改或新增
      ischange() {
        if (this.isEditOrDetailId) {
          this.goodsUpdate()
        }
        else {
          this.addGoods()
        }
      },

      // 新增商品
      addGoods() {
        const data = {
          title: this.title,
          details: this.details,
          remarks: this.remarks,
          secondtitle: this.secondtitle,
          stock: this.stock,
          presentprice: this.presentprice,
          originalprice: this.originalprice,
          isopen: this.radio,
          imgurl: this.imgurl,
          imglist: JSON.stringify(this.imglist),
          categoryid: this.value

        }
        addGoods(data).then(res => {
          if (res.code == 0) {
            console.log('新增商品成功', res)
            this.$message.success('操作成功')
            this.$router.push('/goods/list')

          }
        })
      },

      // 修改商品
      goodsUpdate() {
        const data = {
          title: this.title,
          details: this.details,
          remarks: this.remarks,
          secondtitle: this.secondtitle,
          stock: this.stock,
          presentprice: this.presentprice,
          originalprice: this.originalprice,
          isopen: this.radio,
          imgurl: this.imageUrl,  // 本地展示的图片给后台
          imglist: this.imgList,
          categoryid: this.value,
          id: this.isEditOrDetailId

        }
        goodsUpdate(data).then(res => {
          if (res.code == 0) {
            this.$message.success('操作成功')
            this.$router.push('/goods/list')
          }
        })
      },

      // 获取分类商品列表
      goodsCategoryList() {
        const data = {
          pageNum: 1,
          pageSize: 10,
          name: ''
        }
        console.log(data)
        goodsCategoryList(data).then(res => {
          // console.log('获取分类商品列表', res.data)
          if (res.code === 0) {
            this.options = res.data.list
          }
        })
      },

      // 商品详情
      goodsDetail() {
        const data = {
          id: this.isEditOrDetailId
        }
        goodsDetail(data).then(res => {
          if (res.code == 0) {
            console.log('商品详情列表', res)
            this.title = res.data.title
            this.secondtitle = res.data.secondtitle
            this.details = res.data.details
            this.value = res.data.categoryid
            this.imageUrl = this.img_url + res.data.imgurl
            console.log(this.imageUrl)
            this.radio = res.data.isopen
            this.originalprice = res.data.originalprice
            this.presentprice = res.data.presentprice
            this.stock = res.data.stock
            let imgObj = res.data.imglist.map((item, index) => {
                let url = {
                  name: index,
                  url: this.img_url + item
                }
                return url
              }
            )
            // console.log("imgObj", imgObj)
            this.imgList = imgObj
            console.log('----------', this.imgList)

          }
        })
      },

      // 列表返回
      goBack() {
        this.$router.go(-1)
      },

      // 商品图片上传
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        console.log('this.imageUrl本地要展示', this.imageUrl)
        this.imgurl = res.data // 传给后台
        console.log('传给后台', this.imgurl)
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
        const isLt10M = file.size / 1024 / 1024 < 10

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/png/jpeg 格式!')
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isJPG && isLt10M
      },
      // 轮播图
      handleAvatarSuccess2(res, file, fileList) {
        this.imgList = fileList  //本地l
        let arr = fileList

        this.imglist =
          arr.map((item) => {
            // console.log('item', item)
            // console.log(index)
            return item.response.data
          })

        console.log('轮播图数组', this.imglist)

        // console.log('res1', res)
        // console.log('file1', file)
        console.log('fileList1', fileList)
      },
      handleRemove(file, fileList) {
        console.log('file', file)
        console.log('fileList', fileList)
      }
    }
  }
</script>

<style scoped lang="less">
  .box {
    padding: 20px;

    .card {
      margin-bottom: 20px;
    }

    /*底部按钮*/

    .button {
      margin-bottom: 30px;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }

  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
